{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Approximate q-learning\n",
    "\n",
    "In this notebook you will teach a __tensorflow__ neural network to do Q-learning."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "__Frameworks__ - we'll accept this homework in any deep learning framework. This particular notebook was designed for tensorflow, but you will find it easy to adapt it to almost any python-based deep learning framework."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys, os\n",
    "if 'google.colab' in sys.modules:\n",
    "    %tensorflow_version 1.x\n",
    "    \n",
    "    if not os.path.exists('.setup_complete'):\n",
    "        !wget -q https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/setup_colab.sh -O- | bash\n",
    "\n",
    "        !touch .setup_complete\n",
    "\n",
    "# This code creates a virtual display to draw game images on.\n",
    "# It will have no effect if your machine has a monitor.\n",
    "if type(os.environ.get(\"DISPLAY\")) is not str or len(os.environ.get(\"DISPLAY\")) == 0:\n",
    "    !bash ../xvfb start\n",
    "    os.environ['DISPLAY'] = ':1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import gym\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "env = gym.make(\"CartPole-v0\").env\n",
    "env.reset()\n",
    "n_actions = env.action_space.n\n",
    "state_dim = env.observation_space.shape\n",
    "\n",
    "plt.imshow(env.render(\"rgb_array\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Approximate (deep) Q-learning: building the network\n",
    "\n",
    "To train a neural network policy one must have a neural network policy. Let's build it.\n",
    "\n",
    "\n",
    "Since we're working with a pre-extracted features (cart positions, angles and velocities), we don't need a complicated network yet. In fact, let's build something like this for starters:\n",
    "\n",
    "![img](https://raw.githubusercontent.com/yandexdataschool/Practical_RL/master/yet_another_week/_resource/qlearning_scheme.png)\n",
    "\n",
    "For your first run, please only use linear layers (`L.Dense`) and activations. Stuff like batch normalization or dropout may ruin everything if used haphazardly. \n",
    "\n",
    "Also please avoid using nonlinearities like sigmoid & tanh: since agent's observations are not normalized, sigmoids might be saturated at initialization. Instead, use non-saturating nonlinearities like ReLU.\n",
    "\n",
    "Ideally you should start small with maybe 1-2 hidden layers with < 200 neurons and then increase network size if agent doesn't beat the target score."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import keras\n",
    "import keras.layers as L\n",
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "keras.backend.set_session(sess)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert not tf.test.is_gpu_available(), \\\n",
    "    \"Please complete this assignment without a GPU. If you use a GPU, the code \" \\\n",
    "    \"will run a lot slower due to a lot of copying to and from GPU memory. \" \\\n",
    "    \"To disable the GPU in Colab, go to Runtime → Change runtime type → None.\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network = keras.models.Sequential()\n",
    "network.add(L.InputLayer(state_dim))\n",
    "\n",
    "<YOUR CODE: stack layers!!!1>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def get_action(state, epsilon=0):\n",
    "    \"\"\"\n",
    "    sample actions with epsilon-greedy policy\n",
    "    recap: with p = epsilon pick random action, else pick action with highest Q(s,a)\n",
    "    \"\"\"\n",
    "    \n",
    "    q_values = network.predict(state[None])[0]\n",
    "    \n",
    "    <YOUR CODE>\n",
    "\n",
    "    return <YOUR CODE: epsilon-greedily selected action>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert network.output_shape == (None, n_actions), \"please make sure your model maps state s -> [Q(s,a0), ..., Q(s, a_last)]\"\n",
    "assert network.layers[-1].activation == keras.activations.linear, \"please make sure you predict q-values without nonlinearity\"\n",
    "\n",
    "# test epsilon-greedy exploration\n",
    "s = env.reset()\n",
    "assert np.shape(get_action(s)) == (), \"please return just one action (integer)\"\n",
    "for eps in [0., 0.1, 0.5, 1.0]:\n",
    "    state_frequencies = np.bincount([get_action(s, epsilon=eps) for i in range(10000)], minlength=n_actions)\n",
    "    best_action = state_frequencies.argmax()\n",
    "    assert abs(state_frequencies[best_action] - 10000 * (1 - eps + eps / n_actions)) < 200\n",
    "    for other_action in range(n_actions):\n",
    "        if other_action != best_action:\n",
    "            assert abs(state_frequencies[other_action] - 10000 * (eps / n_actions)) < 200\n",
    "    print('e=%.1f tests passed'%eps)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Q-learning via gradient descent\n",
    "\n",
    "We shall now train our agent's Q-function by minimizing the TD loss:\n",
    "$$ L = { 1 \\over N} \\sum_i (Q_{\\theta}(s,a) - [r(s,a) + \\gamma \\cdot max_{a'} Q_{-}(s', a')]) ^2 $$\n",
    "\n",
    "\n",
    "Where\n",
    "* $s, a, r, s'$ are current state, action, reward and next state respectively\n",
    "* $\\gamma$ is a discount factor defined two cells above.\n",
    "\n",
    "The tricky part is with  $Q_{-}(s',a')$. From an engineering standpoint, it's the same as $Q_{\\theta}$ - the output of your neural network policy. However, when doing gradient descent, __we won't propagate gradients through it__ to make training more stable (see lectures).\n",
    "\n",
    "To do so, we shall use `tf.stop_gradient` function which basically says \"consider this thing constant when doingbackprop\"."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create placeholders for the <s, a, r, s'> tuple and a special indicator for game end (is_done = True)\n",
    "states_ph = keras.backend.placeholder(dtype='float32', shape=(None,) + state_dim)\n",
    "actions_ph = keras.backend.placeholder(dtype='int32', shape=[None])\n",
    "rewards_ph = keras.backend.placeholder(dtype='float32', shape=[None])\n",
    "next_states_ph = keras.backend.placeholder(dtype='float32', shape=(None,) + state_dim)\n",
    "is_done_ph = keras.backend.placeholder(dtype='bool', shape=[None])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#get q-values for all actions in current states\n",
    "predicted_qvalues = network(states_ph)\n",
    "\n",
    "#select q-values for chosen actions\n",
    "predicted_qvalues_for_actions = tf.reduce_sum(predicted_qvalues * tf.one_hot(actions_ph, n_actions), axis=1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gamma = 0.99\n",
    "\n",
    "# compute q-values for all actions in next states\n",
    "predicted_next_qvalues = <YOUR CODE: apply network to get q-values for next_states_ph>\n",
    "\n",
    "# compute V*(next_states) using predicted next q-values\n",
    "next_state_values = <YOUR CODE>\n",
    "\n",
    "# compute \"target q-values\" for loss - it's what's inside square parentheses in the above formula.\n",
    "target_qvalues_for_actions = <YOUR CODE>\n",
    "\n",
    "# at the last state we shall use simplified formula: Q(s,a) = r(s,a) since s' doesn't exist\n",
    "target_qvalues_for_actions = tf.where(is_done_ph, rewards_ph, target_qvalues_for_actions)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#mean squared error loss to minimize\n",
    "loss = (predicted_qvalues_for_actions - tf.stop_gradient(target_qvalues_for_actions)) ** 2\n",
    "loss = tf.reduce_mean(loss)\n",
    "\n",
    "# training function that resembles agent.update(state, action, reward, next_state) from tabular agent\n",
    "train_step = tf.train.AdamOptimizer(1e-4).minimize(loss)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "assert tf.gradients(loss, [predicted_qvalues_for_actions])[0] is not None, \"make sure you update q-values for chosen actions and not just all actions\"\n",
    "assert tf.gradients(loss, [predicted_next_qvalues])[0] is None, \"make sure you don't propagate gradient w.r.t. Q_(s',a')\"\n",
    "assert predicted_next_qvalues.shape.ndims == 2, \"make sure you predicted q-values for all actions in next state\"\n",
    "assert next_state_values.shape.ndims == 1, \"make sure you computed V(s') as maximum over just the actions axis and not all axes\"\n",
    "assert target_qvalues_for_actions.shape.ndims == 1, \"there's something wrong with target q-values, they must be a vector\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Playing the game"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def generate_session(env, t_max=1000, epsilon=0, train=False):\n",
    "    \"\"\"play env with approximate q-learning agent and train it at the same time\"\"\"\n",
    "    total_reward = 0\n",
    "    s = env.reset()\n",
    "    \n",
    "    for t in range(t_max):\n",
    "        a = get_action(s, epsilon=epsilon)       \n",
    "        next_s, r, done, _ = env.step(a)\n",
    "        \n",
    "        if train:\n",
    "            sess.run(train_step,{\n",
    "                states_ph: [s], actions_ph: [a], rewards_ph: [r], \n",
    "                next_states_ph: [next_s], is_done_ph: [done]\n",
    "            })\n",
    "\n",
    "        total_reward += r\n",
    "        s = next_s\n",
    "        if done:\n",
    "            break\n",
    "            \n",
    "    return total_reward"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "epsilon = 0.5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(1000):\n",
    "    session_rewards = [generate_session(env, epsilon=epsilon, train=True) for _ in range(100)]\n",
    "    print(\"epoch #{}\\tmean reward = {:.3f}\\tepsilon = {:.3f}\".format(i, np.mean(session_rewards), epsilon))\n",
    "    \n",
    "    epsilon *= 0.99\n",
    "    assert epsilon >= 1e-4, \"Make sure epsilon is always nonzero during training\"\n",
    "    \n",
    "    if np.mean(session_rewards) > 300:\n",
    "        print(\"You Win!\")\n",
    "        break"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How to interpret results\n",
    "\n",
    "\n",
    "Welcome to the f.. world of deep f...n reinforcement learning. Don't expect agent's reward to smoothly go up. Hope for it to go increase eventually. If it deems you worthy.\n",
    "\n",
    "Seriously though,\n",
    "* __ mean reward__ is the average reward per game. For a correct implementation it may stay low for some 10 epochs, then start growing while oscilating insanely and converges by ~50-100 steps depending on the network architecture. \n",
    "* If it never reaches target score by the end of for loop, try increasing the number of hidden neurons or look at the epsilon.\n",
    "* __ epsilon__ - agent's willingness to explore. If you see that agent's already at < 0.01 epsilon before it's is at least 200, just reset it back to 0.1 - 0.5."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Record videos\n",
    "\n",
    "As usual, we now use `gym.wrappers.Monitor` to record a video of our agent playing the game. Unlike our previous attempts with state binarization, this time we expect our agent to act ~~(or fail)~~ more smoothly since there's no more binarization error at play.\n",
    "\n",
    "As you already did with tabular q-learning, we set epsilon=0 for final evaluation to prevent agent from exploring himself to death."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Record sessions\n",
    "\n",
    "import gym.wrappers\n",
    "\n",
    "with gym.wrappers.Monitor(gym.make(\"CartPole-v0\"), directory=\"videos\", force=True) as env_monitor:\n",
    "    sessions = [generate_session(env_monitor, epsilon=0, train=False) for _ in range(100)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Show video. This may not work in some setups. If it doesn't\n",
    "# work for you, you can download the videos and view them locally.\n",
    "\n",
    "from pathlib import Path\n",
    "from base64 import b64encode\n",
    "from IPython.display import HTML\n",
    "\n",
    "video_paths = sorted([s for s in Path('videos').iterdir() if s.suffix == '.mp4'])\n",
    "video_path = video_paths[-1]  # You can also try other indices\n",
    "\n",
    "if 'google.colab' in sys.modules:\n",
    "    # https://stackoverflow.com/a/57378660/1214547\n",
    "    with video_path.open('rb') as fp:\n",
    "        mp4 = fp.read()\n",
    "    data_url = 'data:video/mp4;base64,' + b64encode(mp4).decode()\n",
    "else:\n",
    "    data_url = str(video_path)\n",
    "\n",
    "HTML(\"\"\"\n",
    "<video width=\"640\" height=\"480\" controls>\n",
    "  <source src=\"{}\" type=\"video/mp4\">\n",
    "</video>\n",
    "\"\"\".format(data_url))"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
